package com.junzhiit.nengji.dao.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.bainaeco.framework.base.dao.AbstractBaseDAO;
import com.bainaeco.framework.common.jdbc.StatementParameter;
import com.bainaeco.framework.enums.IsDelete;
import com.junzhiit.nengji.dao.QuestionTypeDAO;
import com.junzhiit.nengji.model.QuestionType;

@Repository
public class QuestionTypeDAOImpl extends AbstractBaseDAO<QuestionType> implements QuestionTypeDAO {

	@Override
	public List<QuestionType> findAll(int pageNumber, int maxPageRow, String name) {
		StringBuffer sql = new StringBuffer();
		sql.append("select * from `question_type` where is_delete=?");

		StatementParameter params = new StatementParameter();
		params.setInt(IsDelete.NO.toIntValue());

		if (StringUtils.isNotBlank(name)) {
			sql.append(" and name like ?");
			params.setString("%" + name + "%");
		}
		
		sql.append(" order by sort desc,created_time asc");

		return queryForPagingList(sql.toString(), QuestionType.class, params, pageNumber, maxPageRow);
	}

	@Override
	public Integer getTotalCount(String name) {
		StringBuffer sql = new StringBuffer();
		sql.append("select count(id) from `question_type` where is_delete=?");

		StatementParameter params = new StatementParameter();
		params.setInt(IsDelete.NO.toIntValue());

		if (StringUtils.isNotBlank(name)) {
			sql.append(" and name like ?");
			params.setString("%" + name + "%");
		}

		return queryForInt(sql.toString(), params);
	}

	@Override
	public Integer getQuestionTypeExist(String name) {
		StatementParameter params = new StatementParameter();
		StringBuffer sql = new StringBuffer();

		sql.append("select count(*) from `question_type` where is_delete=?");
		params.setInt(IsDelete.NO.toIntValue());

		if (StringUtils.isNotBlank(name)) {
			sql.append(" and name=?");
			params.setString(name);
		}

		return queryForInt(sql.toString(), params);
	}

	@Override
	public List<QuestionType> getList() {
		StringBuffer sql = new StringBuffer();
		sql.append("select id,name from `question_type` where is_delete =?");
		
		StatementParameter params = new StatementParameter();
		params.setInt(IsDelete.NO.toIntValue());
		
		sql.append(" order by sort desc,created_time asc");
		
		return super.queryForList(sql.toString(), QuestionType.class, params);
	}

	@Override
	public Integer getMaxSort() {
		StringBuffer sql = new StringBuffer();
		sql.append("select max(sort) from `question_type` where is_delete=?");
		
		StatementParameter params = new StatementParameter();
		params.setInt(IsDelete.NO.toIntValue());
		
		String str = queryForString(sql.toString(), params);
		if (StringUtils.isNotBlank(str)) {
			return Integer.valueOf(str);
		}
		return 0;
	}

}
